package com.servlet.test; /**
 * @author : DuJiabao
 * @Date : 2021/1/24 17:49
 * @Project : java-web
 * @File : ${FILE_NAME}
 * @Desc :
 */

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class HttpServletTest2 extends HttpServlet {
  /**
   * ServletContext 测试
   *
   * @throws ServletException
   */
  @Override
  public void init() throws ServletException {
    //ServletContext servletContext = getServletConfig().getServletContext();
    ServletContext servletContext = getServletContext();  // 直接通过方法调用获取ServletContext就好了
    String username = servletContext.getInitParameter("username");
    System.out.println(username);
    String password = servletContext.getInitParameter("password");
    System.out.println(password);
//        设置数据 和 initParameter没有关系
    servletContext.setAttribute("username", "root1");
    System.out.println(servletContext.getAttribute("username"));
//      获取当前的工程路径
    System.out.println(servletContext.getContextPath());  // /demo
//        获取部署的绝对路径。部署的内容和工程内容有一个映射关系
    System.out.println(servletContext.getRealPath("/")); //E:\Java\java-web\demo\target\demo-1.0-SNAPSHOT\
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  }

  /**
   * HttpServletRequest 测试
   *
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取请求资源的路径
    System.out.println(request.getRequestURI()); //demo/HttpServletTest2
//        获取请求的统一资源定位符
    System.out.println(request.getRequestURL()); // http://localhost:8080/demo/HttpServletTest2
//        获取客户端的ip
    System.out.println(request.getRemoteHost()); // 127.0.0.1
//        获取请求头的内容
    System.out.println(request.getHeader("Accept-Language"));
//        获取请求的参数（form传上来的数据）
    System.out.println(request.getParameter("username"));
//        获取请求的多个参数（多选列表之类的）
    String[] hobbies = request.getParameterValues("hobby");
    System.out.println(Arrays.toString(hobbies));
    // 获取请求的方式 GET 或 POST
    System.out.println(request.getMethod());
  }
}
